package jwei.apps.helpers;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

/**
 * 
 * @author Jason Wei
 * 
 */
public class PostMethods {

    public static String doPostWithResponse(String mUrl, HashMap<String, String> hm, DefaultHttpClient httpClient) {
        String ret = null;
        HttpResponse response = null;

        HttpPost postMethod = new HttpPost(mUrl);
        if (hm == null) return null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            Iterator<String> it = hm.keySet().iterator();
            String k, v;
            while (it.hasNext()) {
                k = it.next();
                v = hm.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }
            postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpClient.execute(postMethod);
            System.out.println("STATUS CODE: " + String.valueOf(response.getStatusLine().getStatusCode()));
            if (null != response) {
                ret = getResponseBody(response);
            }
        } catch (Exception e) {

        } finally {
        }
        return ret;
    }

    public static void doPostSimple(String mUrl, HashMap<String, String> hm, DefaultHttpClient httpClient)
            throws ClientProtocolException, IOException {
        HttpResponse response = null;
        HttpPost postMethod = new HttpPost(mUrl);
        if (hm == null) return;
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        Iterator<String> it = hm.keySet().iterator();
        String k, v;
        while (it.hasNext()) {
            k = it.next();
            v = hm.get(k);
            nameValuePairs.add(new BasicNameValuePair(k, v));
        }
        postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response = httpClient.execute(postMethod);
        System.out.println("STATUS CODE: " + String.valueOf(response.getStatusLine().getStatusCode()));
    }

    public static HttpResponse doPost(String mUrl, HashMap<String, String> hm, DefaultHttpClient httpClient) {
        HttpResponse response = null;
        HttpPost postMethod = new HttpPost(mUrl);
        if (hm == null) return null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            Iterator<String> it = hm.keySet().iterator();
            String k, v;
            while (it.hasNext()) {
                k = it.next();
                v = hm.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }
            postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            postMethod.setHeader("Content-Type", "application/json");
            postMethod.addHeader("accept", "application/json");
            response = httpClient.execute(postMethod);
            System.out.println("STATUS CODE: " + String.valueOf(response.getStatusLine().getStatusCode()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return response;
    }

    public static HttpResponse doPostJSON(String mUrl, JSONObject params, DefaultHttpClient httpClient) {
        HttpResponse response = null;
        HttpPost postMethod = new HttpPost(mUrl);
        if (params == null) return null;
        try {
            StringEntity se = new StringEntity(params.toString());
            postMethod.setEntity(se);
            postMethod.setHeader("Accept", "application/json");
            postMethod.setHeader("Content-type", "application/json");
            response = httpClient.execute(postMethod);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return response;
    }

    public static String getContentCharSet(final HttpEntity entity) throws ParseException {
        if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
        String charset = null;
        if (entity.getContentType() != null) {
            HeaderElement values[] = entity.getContentType().getElements();
            if (values.length > 0) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }
        return charset;
    }

    public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {
        final String defaultCharset = null;
        if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
        InputStream instream = entity.getContent();
        if (instream == null) { return ""; }
        if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException(
                "HTTP entity too large to be buffered in memory"); }
        String charset = getContentCharSet(entity);
        if (charset == null) {
            charset = defaultCharset;
        }
        if (charset == null) {
            charset = HTTP.DEFAULT_CONTENT_CHARSET;
        }
        Reader reader = new InputStreamReader(instream, charset);
        StringBuilder buffer = new StringBuilder();
        try {
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } finally {
            reader.close();
        }
        return buffer.toString();
    }

    public static String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
        if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        entity.writeTo(bos);
        return bos.toString();
    }

    public static String getResponseBody(HttpResponse response) {
        String response_text = null;
        HttpEntity entity = null;

        try {
            entity = response.getEntity();
            response_text = _getResponseBody(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            if (entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e1) {
                }
            }
        }
        return response_text;
    }
}
